package JavaBase.ArrayTest;

import java.util.Arrays;

/**
 * @Author：coinyang
 * @Project：JavaTest
 * @name：黑洞
 * @Date：2023/8/3 17:30
 */
public class 黑洞 {
    public static void main(String[] args) {
        for (int num = 1000; num <= 9999; num++) {
            int steps = findKaprekarSteps(num);
            System.out.println("Number: " + num + ", Steps: " + steps);
        }
    }

    private static int findKaprekarSteps(int num) {
        int steps = 0;
        while (num != 6174 && steps < 7) {
            int[] arr = getSortedDigits(num);
            int descNum = fromArray(arr, false);
            int ascNum = fromArray(arr, true);
            num = descNum - ascNum;
            steps++;
        }
        return steps;
    }

    private static int[] getSortedDigits(int num) {
        int[] arr = new int[4];
        for (int i = 0; i < 4; i++) {
            arr[i] = num % 10;
            num /= 10;
        }
        Arrays.sort(arr);
        return arr;
    }

    private static int fromArray(int[] arr, boolean descending) {
        int num = 0;
        if (descending) {
            for (int i = 3; i >= 0; i--) {
                num = num * 10 + arr[i];
            }
        } else {
            for (int i : arr) {
                num = num * 10 + i;
            }
        }
        return num;
    }
}
